<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="队伍名称" prop="teamName">
        <el-input
          v-model="queryParams.teamName"
          placeholder="请输入队伍名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所在地区" prop="region">
  <el-select
    v-model="queryParams.region"
    placeholder="请选择所在地区"
    clearable
    @change="handleQuery"
  >
    <el-option
      v-for="region in regions"
      :key="region"
      :label="region"
      :value="region"
    />
  </el-select>
</el-form-item>

      <el-form-item label="队长姓名" prop="teamLeader">
        <el-input
          v-model="queryParams.teamLeader"
          placeholder="请输入队长姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责区域" prop="responsibleArea">
  <el-select
    v-model="queryParams.responsibleArea"
    placeholder="请选择负责区域"
    clearable
    @change="handleQuery"
  >
    <el-option
      v-for="area in responsibleAreas"
      :key="area.value"
      :label="area.label"
      :value="area.value"
    />
  </el-select>
</el-form-item>

<el-form-item label="状态" prop="status">
  <el-select
    v-model="queryParams.status"
    placeholder="请选择状态"
    clearable
    @change="handleQuery"
  >
    <el-option
      v-for="status in statuses"
      :key="status.value"
      :label="status.label"
      :value="status.value"
    />
  </el-select>
</el-form-item>

<el-form-item label="牵头总队" prop="isTotalLeader">
  <el-select
    v-model="queryParams.isTotalLeader"
    placeholder="请选择是否为牵头总队"
    clearable
    @change="handleQuery"
  >
    <el-option :label="'是'" :value="1" />
    <el-option :label="'否'" :value="0" />
  </el-select>
</el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['Task Force:TaskForce:add']"
        >新增</el-button>
      </el-col>
   
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['Task Force:TaskForce:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="TaskForceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="队伍名称" align="center" prop="teamName" />
      <el-table-column label="所在地区" align="center" prop="region" />
      <el-table-column label="队长姓名" align="center" prop="teamLeader" />
      <el-table-column label="联系电话" align="center" prop="phoneNumber" />
      <el-table-column label="负责区域" align="center" prop="responsibleArea" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="牵头总队" align="center">
    <template slot-scope="scope">
      <span v-if="scope.row.isTotalLeader === 1">是</span>
      <span v-else>否</span>
    </template>
  </el-table-column>      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleTeamMembersAllocation(scope.row)"
          >队员分配</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['Task Force:TaskForce:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['Task Force:TaskForce:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改TaskForce对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
  <el-form ref="form" :model="form" :rules="rules" label-width="80px">
    <!-- 队伍名称 -->
    <el-form-item label="队伍名称" prop="teamName" v-if="title === '添加队伍信息' || title === '修改队伍信息'">
      <el-input v-model="form.teamName" placeholder="请输入队伍名称" />
    </el-form-item>


    <el-form-item label="所在地区" prop="region" v-if="title === '添加队伍信息' || title === '修改队伍信息'">
      <el-select
  v-model="form.region"
  placeholder="请选择所在地区"
>
  <el-option
    v-for="region in regions"
    :key="region"
    :label="region"
    :value="region"
  />
</el-select>

</el-form-item>


    <!-- 队长姓名 (仅在添加时显示) -->
    <el-form-item label="队长姓名" prop="teamLeader" v-if="title === '添加队伍信息'">
      <el-input v-model="form.teamLeader" placeholder="请输入队长姓名" />
    </el-form-item>

    <!-- 联系电话 (仅在添加时显示) -->
    <el-form-item label="联系电话" prop="phoneNumber" v-if="title === '添加队伍信息'">
      <el-input v-model="form.phoneNumber" placeholder="请输入联系电话" />
    </el-form-item>

<!-- 负责区域 -->
    <el-form-item label="负责区域" prop="responsibleArea" v-if="title === '添加队伍信息' || title === '修改队伍信息'">
  <el-select
    v-model="form.responsibleArea"
    placeholder="请选择负责区域">
    <el-option
      v-for="area in responsibleAreas"
      :key="area.value"
      :label="area.label"
      :value="area.value"
    />
  </el-select>
</el-form-item>
    <!-- 状态 -->
    <el-form-item label="状态" prop="status" v-if="title === '添加队伍信息' || title === '修改队伍信息'">
  <el-select
    v-model="form.status"
    placeholder="请选择状态"
  >
    <el-option
      v-for="status in statuses"
      :key="status.value"
      :label="status.label"
      :value="status.value"
    />
  </el-select>
</el-form-item>

    <!-- 牵头总队 -->
    <el-form-item label="牵头总队" prop="isTotalLeader" v-if="title === '添加队伍信息' || title === '修改队伍信息'">
      <!-- <el-select v-model="form.isTotalLeader" placeholder="请选择是否为牵头总队">
        <el-option :label="'是'" :value="1" />
        <el-option :label="'否'" :value="0" />
      </el-select> -->

      <el-switch
  v-model="form.isTotalLeader"
  active-value="1"  
  inactive-value="0"
  active-text="是"  
  inactive-text="否" 
></el-switch>

    </el-form-item>
  </el-form>
  
  <div slot="footer" class="dialog-footer">
    <el-button type="primary" @click="submitForm">确 定</el-button>
    <el-button @click="canceldialog">取 消</el-button>
  </div>
</el-dialog>
<!-- 队伍弹出层 -->
<el-dialog :visible.sync="Teampopup" width="800px" append-to-body>
    <h3 class="dialog-title">编辑队伍人员</h3> <!-- 添加标题 -->

      <el-button type="primary" @click="AddTeam">添加</el-button>
    
    <el-table :data="Teamform" border style="width: 100%">
      <el-table-column label="姓名" width="150">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.name"
            placeholder="请输入姓名"
            size="mini"
          />
        </template>
      </el-table-column>
  

      <el-table-column label="身份证件正反面" width="150">
  <template slot-scope="scope">
    <div class="image-container">
      <el-upload
        class="avatar-uploader"
        action="" 
        :show-file-list="false"
        :before-upload="(file) => beforeAvatarUpload(file, scope.row)"
      >
        <img
          :src="scope.row.id_card_image_path || defaultImagePath"
          class="avatar"
          @click="triggerUpload"
          @contextmenu.prevent="openImageDialog(scope.row.id_card_image_path)"
        />
        <i v-if="!scope.row.id_card_image_path" class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
  </template>
</el-table-column>

<el-dialog
  :visible.sync="imageDialogVisible"
  width="30%"
  append-to-body
>
  <img :src="dialogImageUrl" alt="身份证件图片" style="width: 100%;" />
</el-dialog>




      <el-table-column label="电话" width="150">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.phone_number"
            placeholder="请输入电话"
            size="mini"
          />
        </template>
      </el-table-column>

      <el-table-column label="岗位" width="150">
        <template slot-scope="scope">
          <el-select v-model="scope.row.position" placeholder="请选择职位" size="small">
            <el-option
              v-for="position in positions"
              :key="position.value"
              :label="position.label"
              :value="position.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
  <template slot-scope="scope">
    <!-- 判断 scope.row.id 是否存在，如果存在则显示删除按钮 -->
    <el-button
      v-if="scope.row.id"
      size="mini"
      type="text"
      @click="DeleteTeamMembers(scope.row)"
    >删除</el-button>
    
    <!-- 如果 id 不存在，则显示删除项的隐藏按钮 -->
    <el-button
      v-else
      size="mini"
      type="text"
      @click="deleteTempMember(scope.row)"
    >删除</el-button>
  </template>
</el-table-column>


    </el-table>

    <el-button @click="cancel()">取消</el-button>
    <el-button type="primary" @click="SaveTeam()">保存</el-button>

  </el-dialog>
  </div>
</template>

<script>
import { listTaskForce, getTaskForce, delTaskForce, addTaskForce, updateTaskForce, getTeamsByTaskForceId, AddTeam,DeleteMbers, FileTransfer, GetAreaName } from "@/api/Task Force/TaskForce";

export default {
  name: "TaskForce",
  data() {
    return {
      // 队员分配_id
      Teammembersallocation: null,
      // 队伍表单缓存，根据 id 进行缓存
      TeamformBackup: {}, // 以 id 为键的对象
       // 队伍表单参数
      Teamform:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // TaskForce表格数据
      TaskForceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 队伍弹出层
      Teampopup:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teamName: null,
        region: null,
        teamLeader: null,
        phoneNumber: null,
        responsibleArea: null,
        status: null,
        isTotalLeader: null
      },
      // 表单参数
      form: {},
      // 默认图片路竟
      defaultImagePath:'http://localhost:8080/uploads/照片太帅无法显示.jpg',
      imageDialogVisible: false, // 控制 dialog 显示/隐藏
      dialogImageUrl: '',        // 当前放大显示的图片 URL
      // 表单校验
      rules: {
        teamName: [
          { required: true, message: "队伍名称不能为空", trigger: "blur" }
        ],
      },
      regions: [ 
     
    ],
    responsibleAreas: [
      { value: '南宁', label: '南宁' },
      { value: '桂林', label: '桂林' },
      { value: '柳州', label: '柳州' },
    ],
    statuses: [
      { value: '激活', label: '激活' },
      { value: '暂停', label: '暂停' },
      { value: '禁用', label: '禁用' },

    ],
    positions: [
        { value: '队长', label: '队长' },
        { value: '副队长', label: '副队长' },
        { value: '队员', label: '队员' }
      ]
    };
  },
  created() {
    this.getList();
  },
  // 在组件挂载时发送请求
  mounted() {
    this.GetAreaNamer();
  },
  methods: {
    GetAreaNamer(){
      // 获取片区
      GetAreaName().then(response=>{
        this.regions = response.data
        
        
      })

    },

    openImageDialog(imageUrl) {
      if (imageUrl) {
        this.dialogImageUrl = imageUrl; // 设置图片 URL
        this.imageDialogVisible = true; // 打开 dialog
      }
    },
    /** 查询TaskForce列表 */
    getList() {
      this.loading = true;
      listTaskForce(this.queryParams).then(response => {
        this.TaskForceList = response.rows;
      
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    canceldialog() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        teamName: null,
        region: null,
        teamLeader: null,
        phoneNumber: null,
        responsibleArea: null,
        status: null,
        isTotalLeader: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加队伍信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      
      this.reset();
      const id = row.id || this.ids
      getTaskForce(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改队伍信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTaskForce(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTaskForce(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除TaskForce编号为"' + ids + '"的数据项？').then(function() {
        return delTaskForce(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");


      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('Task Force/TaskForce/export', {
        ...this.queryParams
      }, `TaskForce_${new Date().getTime()}.xlsx`)
    },
    /** 队员分配按钮操作 */
    handleTeamMembersAllocation(row){
      this.Teammembersallocation = row.id
      this.Teampopup = true;
      getTeamsByTaskForceId(row.id).then(response => {
        this.Teamform = response.data;
        
        this.Teamform.forEach(member => {
  if (member.id_card_image_path) {
    // 判断 id_card_image_path 是否已经包含了前缀，避免重复追加
    if (!member.id_card_image_path.startsWith('http://localhost:8080')) {
      member.id_card_image_path = 'http://localhost:8080' + member.id_card_image_path;
    }
  }
});
        
      })
      
    },
    // 上转图片
    async beforeAvatarUpload(file, row) {
    if (!row.id) {
      this.$message.error('请先保存队伍成员信息再上传图片！');
      return false; // 阻止上传
    }

    const isJPG = file.type === 'image/jpeg';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
      this.$message.error('上传头像图片只能是 JPG 格式!');
      return false;
    }
    if (!isLt2M) {
      this.$message.error('上传头像图片大小不能超过 2MB!');
      return false;
    }

    // 手动上传文件
    const formData = new FormData();
    formData.append('file', file);
    formData.append('id', row.id); // 添加队员的id

    try {
      const response = await FileTransfer(formData);      
      this.$message.success('上传成功！');
    this.refreshTeamList(this.Teammembersallocation)
      
    } catch (error) {
      this.$message.error('上传失败！');
      return false;
    }

    return true; // 上传成功，允许继续
  },
  handleAvatarSuccess(response, file, fileList) {
    console.log('上传成功:', file.name);
    console.log(response);
    console.log(fileList);


  },
  triggerUpload() {
    console.log('图片上传触发');
  },
    // 删除队伍人员
    DeleteTeamMembers(row){
      this.$modal.confirm('是否确认删除队伍人员"' + row.name + '"的数据项？').then(function() {
        return DeleteMbers(row.id);

      }).then(() => {
        this.$modal.msgSuccess("删除成功");
  // 从 Teamform 中移除被删除的成员，前端数据更新
  this.Teamform = this.Teamform.filter(member => member.id !== row.id);
      // this.refreshTeamList(row.team_id); // 刷新队员列表
        
      }).catch(() => {});
      
    },
    // 删除没有ID的临时队员项
  deleteTempMember(row) {
    // 从 Teamform 中删除该项
    this.Teamform = this.Teamform.filter(member => member !== row);
  },
  // 刷新队伍人员列表
  refreshTeamList(team_id) {
    getTeamsByTaskForceId(team_id).then(response => {
      this.Teamform = response.data;

      this.Teamform.forEach(member => {
  if (member.id_card_image_path) {
    // 判断 id_card_image_path 是否已经包含了前缀，避免重复追加
    if (!member.id_card_image_path.startsWith('http://localhost:8080')) {
      member.id_card_image_path = 'http://localhost:8080' + member.id_card_image_path;
    }
  }
});
    });
  },

    // 保存队伍
    SaveTeam() {
  // 不再从缓存恢复数据，直接使用当前修改后的 Teamform 数据

  // 过滤掉 name、phone_number 和 position 同时为空的项
  const validMembers = this.Teamform.filter(member => {
    return !(member.name === '' && member.phone_number === '' && member.position === '');
  });

  // 检查是否有多个 "队长"
  const captainCount = validMembers.filter(member => member.position === '队长').length;
  if (captainCount > 1) {
    this.$message.error("不能有多个队长，请检查并修改！");
    return; // 阻止提交
  }

  // 检查是否至少有一个 "队长"
  if (captainCount === 0) {
    this.$message.error("必须至少有一个队长，请添加队长！");
    return; // 阻止提交
  }

  // 仅保存有效的成员到数据库
  const updatedMembers = validMembers.map(member => ({
    id: member.id,
    name: member.name,
    team_id: this.Teammembersallocation, 
    phone_number: member.phone_number,
    id_card_image_path: member.id_card_image_path,
    position: member.position
  }));

  console.log(updatedMembers);

  // 调用后台接口保存成员信息
  AddTeam(updatedMembers).then(response => {
    this.$modal.msgSuccess("保存成功");
    // 更新缓存，保存到缓存中
    this.TeamformBackup[this.Teammembersallocation] = JSON.parse(JSON.stringify(this.Teamform)); // 更新缓存数据

    this.Teampopup = false; // 关闭弹出框
    this.getList();
  }).catch(error => {
    this.$modal.msgError("保存失败：" + error.message);
  });
},

    // 队伍分配弹出层打开时恢复缓存的数据
    handleTeamMembersAllocation(row) {
      this.Teammembersallocation = row.id;
      this.Teampopup = true;

      // 如果当前 id 已有缓存数据，恢复缓存的数据
      if (this.TeamformBackup[this.Teammembersallocation]) {
        this.Teamform = JSON.parse(JSON.stringify(this.TeamformBackup[this.Teammembersallocation])); // 恢复缓存
      } else {
        // 如果没有缓存数据，则从后台加载
        getTeamsByTaskForceId(row.id).then(response => {
          this.Teamform = response.data;
          this.Teamform.forEach(member => {
            if (member.id_card_image_path) {
              if (!member.id_card_image_path.startsWith('http://localhost:8080')) {
                member.id_card_image_path = 'http://localhost:8080' + member.id_card_image_path;
              }
            }
          });
        });
      }
    },
    // 隐藏队伍
    cancel() {
      this.Teampopup = false;
      if (this.Teammembersallocation) {
        // 根据当前队伍的 id 缓存当前表单数据
        this.TeamformBackup[this.Teammembersallocation] = JSON.parse(JSON.stringify(this.Teamform)); // 深拷贝
      }
    },
    //添加队伍
    AddTeam(){
      
      this.Teamform.push({
        name: '',
        id_card_image_path: '',
        phone_number: '',
        position: ''
      });
    },

     // 动态生成上传的API地址
  uploadUrl(id) {
    console.log(id);
    
    return FileTransfer(id) 
  },

  }
};
</script>
<style scoped>
.dialog-title {
  font-size: 18px; /* 标题字体大小 */
  margin-bottom: 20px; /* 标题与列表之间的间距 */
  text-align: center; /* 标题居中 */
}

.image-container {
  text-align: center;
}

.avatar-uploader {
  width: 80px;
  height: 80px;
  border: 1px dashed #d3d3d3; /* 虚线边框 */
  border-radius: 5px;
  overflow: hidden;
  position: relative;
  background-color: #fff; /* 背景颜色 */
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover; /* 保持图片比例 */
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.el-input {
  border-radius: 4px; /* 圆角输入框 */
  border: 1px solid #d3d3d3; /* 边框 */
}

.el-select {
  border-radius: 4px; /* 圆角选择框 */
  border: 1px solid #d3d3d3; /* 边框 */
}
 
</style>